#include "tools/log_util.h"

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <time.h>

// void print_log(char* level, char *scope_file, char *scope_function, char *message) {
//     printf("[%s]     [%s: %s]     %s\n", level, scope_file, scope_function, message);
// }

void print_log(const char* level, const char* scope_file, const char* scope_function, const char* format, ...) {
    va_list args;
    
    // 计算格式化字符串所需长度
    va_start(args, format);
    int needed_len = vsnprintf(NULL, 0, format, args) + 1; // +1 为终止符'\0'
    va_end(args);

    if (needed_len <= 0) {
        fprintf(stderr, "格式化消息失败\n");
        return;
    }

    // 动态分配缓冲区
    char* buffer = (char*)malloc(needed_len);
    if (!buffer) {
        fprintf(stderr, "内存分配失败\n");
        return;
    }

    // 实际格式化字符串
    va_start(args, format);
    vsnprintf(buffer, needed_len, format, args);
    va_end(args);

    // 输出日志
    printf("[%s]     [%s: %s]     %s\n", level, scope_file, scope_function, buffer);

    // 释放缓冲区
    free(buffer);
}

void format_output_log(const char* level, const char* scope_file, int line, const char* scope_function, const char* format, ...) {
    va_list args;
    
    // 计算格式化字符串所需长度
    va_start(args, format);
    int needed_len = vsnprintf(NULL, 0, format, args) + 1; // +1 为终止符'\0'
    va_end(args);

    if (needed_len <= 0) {
        fprintf(stderr, "格式化消息失败\n");
        return;
    }

    // 动态分配缓冲区
    char* buffer = (char*)malloc(needed_len);
    if (!buffer) {
        fprintf(stderr, "内存分配失败\n");
        return;
    }

    // 实际格式化字符串
    va_start(args, format);
    vsnprintf(buffer, needed_len, format, args);
    va_end(args);

    // 时间
    time_t now = time(NULL);
    struct tm *t = localtime(&now);
    char time_str[32];
    strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", t);

    // 输出日志
    printf("[%s]   [%s]    [%s : %d]  [%s]       %s\n", time_str, level, scope_file, line, scope_function, buffer);

    // 释放缓冲区
    free(buffer);
}